#将py文件打包成exe文件
#命令：在pip安装路径中，用终端打开pyinstaller
#pyinstaller -F -w 文件名
#最终以管理员权限取得打开生成的可执行文件（第一次可行，再次以管理员权限取得，就打不开了）
import datetime
import tkinter
import tkinter.scrolledtext
import tkinter.messagebox
import tkinter.filedialog
import tkinter.ttk
import socket
import pymysql
import random
import threading
import time
import struct
import struct
import sys
import string
import docx
import xlrd
import openpyxl
import os
#创建tkinter应用程序主窗口,并自定义关闭窗口的事件处理函数：
root=tkinter.Tk()
root.iconbitmap("icon.ico")#定义图标
root.geometry('360x340+400+300')
root.resizable(False,False)
root.title('课程教学管理系统---教师端')

#关闭程序时，取消点名，收作业，接受提问以及接受客户端查询等情况
#避免端口一直占用
def closeWindow():
    
    #结束点名
    if int_canDianming.get()==1:
        int_canDianming.set(0)
        
    #结束收作业
    if int_zuoye.get()==1:
        int_zuoye.set(0)

    #结束学生主动提问
    if int_xueshengTiwen.get()==1:
        int_xueshengTiwen.set(0)

    #结束服务状态
    if int_server.get()==1:
        int_server.set(0)
        
    root.destroy()
    
#绑定事件处理处理函数
root.protocol('VM_DELETE_WINDOW',closeWindow)

#定义一个通用类，封装系统中频繁使用的功能

#通用功能类
class Common:
    #查询数据库，获取学生专业列表(成功)
    def getZhuanye():
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute('SELECT distinct(zhuanye) FROM STUDENTS')
        temp=cur.fetchall()
        conn.close()
        xueshengZhuanye=[]
        for line in temp:
            xueshengZhuanye.append(line[0])
        return xueshengZhuanye
    #获取指定专业的学生名单(成功)
    def getXuehaoXingming(zhuanye):
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute("SELECT xuehao,xingming FROM STUDENTS WHERE zhuanye='"+zhuanye+"' ORDER BY xuehao")
        temp=cur.fetchall()
        conn.close()
        xueshengXinxi=[]
        for line in temp:
            xueshengXinxi.append(line[0]+','+line[1])
        return xueshengXinxi
    #获取指定学号的出勤次数（成功）
    def getChuqinCishu(xuehao):
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute("SELECT count(xuehao) FROM DIANMING WHERE xuehao='"+xuehao+"'")
        temp=cur.fetchall()
        conn.close()
        xueshengXinxi=[]
        for line in temp:
            xueshengXinxi.append(line[0])
        return xueshengXinxi
    #获取指定学号的学生提问总得分(成功)
    def getTiwenDefen(xuehao):
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute("SELECT sum(defen) FROM TIWEN WHERE xuehao='"+xuehao+"'")
        temp=cur.fetchall()
        conn.close()
        xueshengXinxi=[]
        for line in temp:
            xueshengXinxi.append(line[0])
        return xueshengXinxi
    #获取指定学号的学生主动提问次数(成功)（方法入口参数：字符串类型）
    def getZhudongTiwenCishu(xuehao):
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute("SELECT count(xuehao) FROM XUESHENGTIWEN WHERE xuehao='"+xuehao+"'AND wenti NOT LIKE '老师回复%'")
        temp=cur.fetchall()
        conn.close()
        xueshengXinxi=[]
        for line in temp:
            xueshengXinxi.append(line[0])
        return xueshengXinxi
    #查看学生在线考试得分(成功)
    def getKaoshiDefen(xuehao):
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute("SELECT count(xuehao) FROM KAOSHI WHERE xuehao='"+xuehao+"'AND SHIFOUZHENGQUE='N'")
        temp=cur.fetchall()
        conn.close()
        xueshengXinxi=[]
        for line in temp:
            xueshengXinxi.append(line[0])
        return xueshengXinxi
    #获取指定SQL语句查询结果
    def getDataBySQL(sql):
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute(sql)
        result=cur.fetchall()
        conn.close()
        return result
    #执行SQL语句（成功）
    def doSQL(sql):
        conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
        cur=conn.cursor()
        cur.execute(sql)
        conn.commit()
        conn.close()

    #当前日期时间，格式为“年-月-日 时：分：秒”（成功）
    def getCurrentDateTime():
        return str(datetime.datetime.now())[:19]
    #当前日期时间之前一个半小时前的时间，主要用来避免重复点名(成功)
    def getStartDateTime():
        now=datetime.datetime.now()
        now=now+datetime.timedelta(minutes=-90)
        return str(now)[:19]
#===========================================================================
    #题库导入功能
#===========================================================================
    #-------学生名单导入（成功）-----------
    def buttonImportXueshengXinxiClick():
        filename=tkinter.filedialog.askopenfilename(title='请选择Excel文件',
                                                    filetypes=[('Excel Files','*.xlsx')])
        if filename:
            #读取数据并导入数据库
            
            workbook=xlrd.open_workbook(filename=filename)
            sheet1=workbook.sheet_by_index(0)
            #Excel文件必须含四列，分别为课程名称,学号，姓名，专业年级
            #a=sheet1.ncols
            #print(a)
            #b=sheet1.nrows
            #print(b)
            if sheet1.ncols!=4:
                tkinter.messagebox.showerror(title='抱歉',
                                             message='Excel文件格式不对')
                return
            for rowIndex in range(0,sheet1.nrows):#遍历Excel每一行
                row=sheet1.row(rowIndex)
                sql="INSERT INTO STUDENTS VALUES('"+str(row[0].value)+"','"+str(row[1].value)+"','"+str(row[2].value)+"','"+str(row[3].value)+"')"
                Common.doSQL(sql)
            tkinter.messagebox.showinfo(title='恭喜',message='导入成功')
    buttonImportXueshengXinxi=tkinter.Button(root,text='导入学生信息',
                                             command=buttonImportXueshengXinxiClick)
    buttonImportXueshengXinxi.place(x=20,y=20,height=30,width=100)
    #--------题库导入-----------
    def buttonDaoruTikuClick():
        filename=tkinter.filedialog.askopenfilename(title='请选择Excel 2010或Word 2010版本的题库文件',
                                                    filetypes=[('Excel Files','*.xlsx'),('Word Files','*.docx')])
        if filename:
            #读取数据并导入数据库
            #Excel文件（成功）
            if filename.endswith('.xlsx'):
                workbook=xlrd.open_workbook(filename=filename)
                sheet1=workbook.sheet_by_index(0)
                #Excel文件必须包含5列，分别为标号，课程名称，章节，题目，答案
                if sheet1.ncols!=5:
                    tkinter.messagebox.showerror(title='抱歉',
                                                 message='题库格式不对')
                    return
                for rowIndex in range(0,sheet1.nrows):
                    row=sheet1.row(rowIndex)
                    sql="INSERT INTO TIKU VALUES('"+str(row[0].value)+"','"+str(row[1].value)+"','"+str(row[2].value)+"','"+str(row[3].value)+"','"+str(row[4].value)+"')"
                    Common.doSQL(sql)
                tkinter.messagebox.showinfo(title='恭喜',
                                            message='导入成功')
                
    buttonDaoruTiku=tkinter.Button(root,text='导入题库',
                                   command=buttonDaoruTikuClick)
    buttonDaoruTiku.place(x=20,y=220,height=30,width=100)
#===========================================================================
    #点名与加分功能
#===========================================================================
    #控制是否可以点名的变量，1表示可以，0表示不可以
int_canDianming=tkinter.IntVar(root,value=0)
def thread_Dianming():
    #开始监听
    global sockDianming
    sockDianming=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockDianming.bind(('',30000))##############################################################
    sockDianming.listen(200)
    while int_canDianming.get()==1:
        try:
            #接收一个客户端连接
            conn,addr=sockDianming.accept()
        except:
            return
        data=conn.recv(1024)
        data=data.decode()
        print(data)
        try:
            xuehao,xingming,mac=data.split(',')    #客户端发来的信息格式为“学号”，“姓名”,“mac地址”
        except:
            conn.sendall('repeat'.encode())
            conn.close()
        #防SQL注入
        xuehao=xuehao.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
        xingming = xingming.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
    
        #首先检查学号与姓名是否匹配，并且与数据库中的学生信息一致
        sqlIfMatch="SELECT count(xuehao) FROM STUDENTS WHERE xuehao='"+xuehao+"' AND xingming='"+xingming+"'"
        if Common.getDataBySQL(sqlIfMatch)[0][0]!=1:#[0][0]这块不太懂,cursor的坐标是二维的？
            conn.sendall('notmatch'.encode())
            conn.close()
        else:
            #记录该学生点名信息：学号，时间
            #并反馈给客户端点名成功，然后客户端关闭连接
            currentTime=Common.getCurrentDateTime()
            #获取一个半小时之前的时间
            startTime=Common.getStartDateTime()
            #查看是否已经点过名，避免一个半小时内重复点名
            sqlShifouChongfuDianming="SELECT count(xuehao) FROM DIANMING WHERE xuehao='"+xuehao+"' AND shijian>='"+startTime+"'"
            print(mac)
            sqlMacShifouChongfu="SELECT count(mac) FROM DIANMING WHERE mac='"+mac+"' AND shijian>='"+startTime+"'"#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            print( Common.getDataBySQL(sqlMacShifouChongfu))
            if Common.getDataBySQL(sqlShifouChongfuDianming)[0][0]!=0 or len(mac)!=12 or Common.getDataBySQL(sqlMacShifouChongfu)[0][0]!=0:
                conn.sendall('repeat'.encode())
                conn.close()
            else:
                #检查是否代替点名，根据学生端IP地址识别
                sqlShifouDaiDianming="SELECT count(ip) FROM DIANMING WHERE ip='"+addr[0]+"' AND shijian>='"+startTime+"'"
                if Common.getDataBySQL(sqlShifouDaiDianming)[0][0]!=0:
                    conn.sendall('daidianming'.encode())
                    conn.close()
                else:
                    #点名
                    sqlDianming="INSERT INTO DIANMING VALUES('"+xuehao+"','"+currentTime+"','"+addr[0]+"')"
                    Common.doSQL(sqlDianming)
                    conn.sendall('ok'.encode())
                    conn.close()
    sockDianming.close()
    sockDianming=None


#===============================================================================        
#查看学生信息
#===============================================================================
int_windowChakanXueshengXinxi=tkinter.IntVar(root,value=0)        
class windowChakanXueshengXinxi:
    def __init__(self,root,myTitle):
        self.top=tkinter.Toplevel(root,width=350,height=400)
        self.top.title(myTitle)
        self.top.attributes('-topmost',1)

        #用组合框来显示学生的专业
        #调用通用功能函数类中的方法获取学生的专业
        xueshengZhuanye=Common.getZhuanye()
        comboboxZhuanye=tkinter.ttk.Combobox(self.top,values=xueshengZhuanye)
        comboboxZhuanye.place(x=20,y=20,height=20,width=100)

        def buttonChakanClick():
            zhuanye=comboboxZhuanye.get()
            if not zhuanye:
                tkinter.messagebox.showerror(title='抱歉',
                                             message='请选择专业')
                return
            #根据选择的专业获取专业所有学生名单，格式为“学号，姓名”
            temp=Common.getXuehaoXingming(zhuanye)
            for row in treeXueshengMingdan.get_children():#删除原有的所有行
                treeXueshengMingdan.delete(row)
            iii=0
            for student in temp:
                student=student.split(',')#分隔学号和姓名
                treeXueshengMingdan.insert('',iii,values=(student[0],student[1]))
                iii=iii+1
        #创建表格，设置表头，show='headings'用来隐藏树形控件的默认首列
        self.frame=tkinter.Frame(self.top)
        self.frame.place(x=20,y=50,height=280,width=200)
        #垂直滚动条
        scrollBar=tkinter.Scrollbar(self.frame)
        scrollBar.pack(side=tkinter.RIGHT,fill=tkinter.Y)
        #使用树形控件实现表格
        treeXueshengMingdan=tkinter.ttk.Treeview(self.frame,columns=('col1','col2'),show="headings",yscrollcommand=scrollBar.set)
        treeXueshengMingdan.column('col1',width=90,anchor='center')
        treeXueshengMingdan.column('col2',width=90,anchor='center')
        treeXueshengMingdan.heading('col1',text='学号')
        treeXueshengMingdan.heading('col2',text='姓名')
        #双击某行学生信息，双击实现离线点名（未成功）
        def onDBClick(event):
            if not treeXueshengMingdan.selection():
                tkinter.messagebox.showerror('很抱歉','请选择学生')
                return
            item=treeXueshengMingdan.selection()[0]
            xuehaoDianming=treeXueshengMingdan.item(item,'values')[0]
            xingmingDianming=treeXueshengMingdan.item(item,'values')[1]
            currentTime=Common.getCurrentDateTime()
            #获取一个半小时之前的时间
            startTime=Common.getStartDateTime()
            #查看是否已经点名过，避免一个半小时内重复点名
            sqlShifouChongfuDianming="SELECT count(xuehao) FROM DIANMING WEHRE xuehao='"+xuehaoDianming+"'AND shijian>='"+startTime+"' "
            if Common.getDataBySQL(sqlShifouChongfuDianming)[0][0]!=0:
                tkinter.messagebox.showerror('很抱歉',xuehaoDianming+','+xingmingDianming+'重复点名')
                return
            #点名
            sqlDianming="INSERT INTO DIANMING VALUES('"+xuehaoDianming+"','"+currentTime+"')"
            Common.getDataBySQL(sqlDianming)
            tkinter.messagebox.showinfo('恭喜',xuehaoDianming+','+xingmingDianming+'点名成功')
        treeXueshengMingdan.bind("<Double-1>",onDBClick)
        treeXueshengMingdan.pack(side=tkinter.LEFT,fill=tkinter.Y)
        #树形控件与垂直滚动条结合
        scrollBar.config(command=treeXueshengMingdan.yview)
        buttonChakan=tkinter.Button(self.top,text='查看',command=buttonChakanClick)
        buttonChakan.place(x=130,y=20,height=20,width=40)
        def buttonJiafenClick():#(成功)
            #首先选择一个学生，然后加分
            #为该学生添加一个提问得分，5分
            if not treeXueshengMingdan.selection():
                tkinter.messagebox.showerror('很抱歉','请选择学生')
                return
            item=treeXueshengMingdan.selection()[0]
            xuehaoJiafen=treeXueshengMingdan.item(item,'values')[0]
            sqlJiafen="INSERT INTO TIWEN VALUES('"+xuehaoJiafen+"','"+Common.getCurrentDateTime()+"',5)"
            Common.doSQL(sqlJiafen)
            tkinter.messagebox.showinfo('恭喜','加分成功')
        buttonJiafen=tkinter.Button(self.top,text='听课认真加分',command=buttonJiafenClick)
        buttonJiafen.place(x=30,y=350,height=20,width=100)

        def buttonJianfenClick():#（成功）
            #首先选择一个学生，然后减分
            #为该学生添加一个提问得分，-5分
            if not treeXueshengMingdan.selection():
                tkinter.messagebox.showerror('很抱歉','请选择学生')
                return
            item=treeXueshengMingdan.selection()[0]
            xuehaoJianfen=treeXueshengMingdan.item(item,'values')[0]
            sqlJianfen="INSERT INTO TIWEN VALUES('"+xuehaoJianfen+"','"+Common.getCurrentDateTime()+"',-5)"
            Common.doSQL(sqlJianfen)
            tkinter.messagebox.showinfo('恭喜','减分成功')
        buttonJianfen=tkinter.Button(self.top,text='听课不认真减分',command=buttonJianfenClick)
        buttonJianfen.place(x=140,y=350,height=20,width=100)
        labelTishi=tkinter.Label(self.top,text='温馨提示：双击表格中的某个学生可以离线点名，或者补点名。',fg='red')
        labelTishi.place(x=10,y=380,height=20)

def buttonChakanXueshengxinxiClick():
    if int_windowChakanXueshengXinxi.get()==0:
        int_windowChakanXueshengXinxi.set(1)
        w1=windowChakanXueshengXinxi(root,'查看学生信息')
        buttonChakanXueshengXinxi.wait_window(w1.top)
        int_windowChakanXueshengXinxi.set(0)
buttonChakanXueshengXinxi=tkinter.Button(root,text='查看学生信息',command=buttonChakanXueshengxinxiClick)
buttonChakanXueshengXinxi.place(x=130,y=20,height=30,width=100)

def buttonIPClick():#获取并输出本机IP地址(成功)
    IP=socket.gethostbyname(socket.gethostname())
    tkinter.messagebox.showinfo(title='本机IP地址',message=IP)
buttonIP=tkinter.Button(root,text='查看本机IP地址',command=buttonIPClick)
buttonIP.place(x=240,y=20,height=30,width=100)

int_canDianming=tkinter.IntVar(root,value=0)#是否可以点名，1表示可以，0表示不可以

#开始点名
def buttonStartDianmingClick():
    '''if int_zuoye.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在收作业')
        return
    '''
    if int_canDianming.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在点名')
        return
        
    tkinter.messagebox.showinfo('恭喜','设置成功,现在开始点名')
    int_canDianming.set(1)#开始点名
    global tDianming_id
    t=threading.Thread(target=thread_Dianming)
    t.start()
    tDianming_id=t.ident
buttonStartDianming=tkinter.Button(root,text='开始点名',command=buttonStartDianmingClick)
buttonStartDianming.place(x=20,y=60,height=30,width=100)

def buttonStopDianmingClick():
    if int_canDianming.get()==0:
        tkinter.messagebox.showerror('很抱歉','还没开始点名')
        return
    int_canDianming.set(0)#停止点名
    sockDianming.close()
    time.sleep(0.1)
    sql='SELECT zhuanye FROM STUDENTS WHERE xuehao=(SELECT xuehao FROM DIANMING WHERE shijian<="'+Common.getCurrentDateTime()+'" ORDER BY shijian DESC limit 1)'
    currentZhuanye=Common.getDataBySQL(sql)[0][0]
    sql="SELECT count(zhuanye) FROM STUDENTS WHERE zhuanye='"+currentZhuanye+"'"
    totalRenshu=Common.getDataBySQL(sql)[0][0]

    sql='SELECT count(xuehao) FROM DIANMING WHERE shijian<="'+Common.getCurrentDateTime()+'" AND shijian>="'+Common.getStartDateTime()+'"'
    totalShidao=Common.getDataBySQL(sql)[0][0]

    message='设置成功,现在停止点名！\n当前点名专业：'+currentZhuanye+'\n应到人数：'+str(totalRenshu)+'\n实到人数'+str(totalShidao)
    tkinter.messagebox.showinfo('恭喜',message)
    #最好能显示本次点名实到人数
onStopDianming=tkinter.Button(root,text='结束点名',command=buttonStopDianmingClick)
onStopDianming.place(x=130,y=60,height=30,width=100)

#===============================================================================
#查看考勤情况(成功)
#===============================================================================
int_windowChakanKaoqinXinxi=tkinter.IntVar(root,value=0)
class windowChakanKaoqinXinxi:
    def __init__(self,root,myTitle):
        self.top=tkinter.Toplevel(root,width=320,height=400)
        self.top.title(myTitle)
        self.top.attributes('-topmost',1)
        #组合框选择专业，或文本框查看特定学号学生的出勤情况
        xueshengZhuanye=Common.getZhuanye()#学生专业
        comboboxZhuanye=tkinter.ttk.Combobox(self.top,values=xueshengZhuanye)
        def comboboxZhuanyeChange(event):
            zhuanye=comboboxZhuanye.get()
            if zhuanye:
                xueshengs=Common.getXuehaoXingming(zhuanye)
                comboboxXuehao['values']=xueshengs
        comboboxZhuanye.bind('<<ComboboxSelected>>',comboboxZhuanyeChange)
        comboboxZhuanye.place(x=20,y=20,height=20,width=130)
        def chakanZhuanye():#输出该专业所有学生的出勤情况
            zhuanye=comboboxZhuanye.get()
            if not zhuanye:
                tkinter.messagebox.showerror('很抱歉','请选择专业')
                return
            sql="SELECT STUDENTS.xuehao,STUDENTS.xingming,DIANMING.shijian FROM STUDENTS,DIANMING WHERE STUDENTS.xuehao=DIANMING.xuehao AND STUDENTS.zhuanye='"+zhuanye+"' ORDER BY STUDENTS.xuehao"
            temp=Common.getDataBySQL(sql)

            for row in treeXueshengMingdan.get_children():#删除原有的所有行
                treeXueshengMingdan.delete(row)
            iii=0#标记正在操作的行的标志
            for student in temp:
                treeXueshengMingdan.insert('',iii,values=(student[0],student[1],student[2]))
                iii=iii+1
        buttonZhuanye=tkinter.Button(self.top,text='按专业查看',command=chakanZhuanye)
        buttonZhuanye.place(x=160,y=20,height=20,width=80)
        comboboxXuehao=tkinter.ttk.Combobox(self.top,)
        comboboxXuehao.place(x=20,y=60,height=20,width=130)
        def chakanXuehao():#按学号查看学生出勤情况
            for row in treeXueshengMingdan.get_children():#删除原有的所有行
                treeXueshengMingdan.delete(row)
            xueshengXinxi=comboboxXuehao.get()
            if not xueshengXinxi:
                tkinter.messagebox.showerror('很抱歉','请选择学生')
                return
            xuehaoKaoqin=xueshengXinxi.split(',')[0]
            sql="SELECT STUDENTS.xuehao,STUDENTS.xingming,DIANMING.shijian FROM STUDENTS,DIANMING WHERE STUDENTS.xuehao=DIANMING.xuehao AND DIANMING.xuehao='"+xuehaoKaoqin+"'"
            temp=Common.getDataBySQL(sql)

            iii=0
            for student in temp:
                treeXueshengMingdan.insert('',iii,values=(student[0],student[1],student[2]))
                iii=iii+1
        buttonXuehao=tkinter.Button(self.top,text='按学号查看',command=chakanXuehao)
        buttonXuehao.place(x=160,y=60,height=20,width=80)

        #创建表格，设置表头，show="headings"用来隐藏树形控件的默认首列（这句话是什么意思？？？？？）
        self.frame=tkinter.Frame(self.top)
        self.frame.place(x=20,y=90,width=290,height=280)
        #垂直滚动条
        scrollBar=tkinter.Scrollbar(self.frame)
        scrollBar.pack(side=tkinter.RIGHT,fill=tkinter.Y)
        #使用树形控件实现表格
        treeXueshengMingdan=tkinter.ttk.Treeview(self.frame,columns=('col1','col2','col3'),show="headings",yscrollcommand=scrollBar.set)
        treeXueshengMingdan.column('col1',width=70,anchor='center')
        treeXueshengMingdan.column('col2',width=60,anchor='center')
        treeXueshengMingdan.column('col3',width=140,anchor='center')
        treeXueshengMingdan.heading('col1',text='学号')
        treeXueshengMingdan.heading('col2',text='姓名')
        treeXueshengMingdan.heading('col3',text='出勤时间')
        treeXueshengMingdan.pack(side=tkinter.LEFT,fill=tkinter.Y)
        #树形控件与垂直滚动条结合
        scrollBar.config(command=treeXueshengMingdan.yview)

def buttonChakanKaoqinXinxiClick():
    if int_windowChakanKaoqinXinxi.get()==0:
        w1=windowChakanKaoqinXinxi(root,'查看出勤情况')
        buttonChakanKaoqinXinxi.wait_window(w1.top)
        int_windowChakanKaoqinXinxi.set(0)
buttonChakanKaoqinXinxi=tkinter.Button(root,text='查看出勤情况',command=buttonChakanKaoqinXinxiClick)
buttonChakanKaoqinXinxi.place(x=240,y=60,height=30,width=100)

int_windowTiwen=tkinter.IntVar(root,value=0)
studentInformation=tkinter.StringVar('')
#===============================================================================
#提问功能(成功)
#===============================================================================
class windowTiwen:
    def __init__(self,root,myTitle,already=[]):
        '''already表示已经提问的学生名单
            这里充分利用列表作为函数默认值参数时的记忆性'''#这块理解一下！！！！！
        self.top=tkinter.Toplevel(root,width=300,height=150)
        self.top.title(myTitle)
        self.top.attributes('-topmost',1)

        xueshengZhuanye=Common.getZhuanye()#学生专业
        comboboxZhuanye=tkinter.ttk.Combobox(self.top,values=xueshengZhuanye)
        comboboxZhuanye.place(x=20,y=20,height=20,width=100)
        xueshengXuehao=tkinter.StringVar(self.top,value='')#被提问到的学生学号
        def buttonTiwenClick():
            zhuanye=comboboxZhuanye.get()
            if not zhuanye:
                tkinter.messagebox.showerror('很抱歉','请选择一个专业')
                return
            #从该专业学生名单中随机选取一个
            conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
            cur=conn.cursor()
            cur.execute("SELECT xuehao,xingming FROM STUDENTS WHERE zhuanye='"+zhuanye+"'")
            allStudents=cur.fetchall()
            conn.close()
            #任何同学不会在同一节课被提问两次
            while True:
                temp=random.choice(allStudents)
                if temp not in already:
                    already.append(temp)
                    break
            xuehao=temp[0]
            xueshengXuehao.set(xuehao)
            studentInformation.set('本次中奖同学为：'+str((temp[0],temp[1])))
        buttonTiwen=tkinter.Button(self.top,text='看看谁最幸运',command=buttonTiwenClick)
        buttonTiwen.place(x=130,y=20,height=20,width=80)
        comboboxDefen=tkinter.ttk.Combobox(self.top,values=['-2','-1','0','1','2','3','4','5'])#这一行在干什么？？得分？？
        comboboxDefen.place(x=20,y=50,height=20,width=100)
        def buttonDefenClick():
            if xueshengXuehao.get()=='':
                tkinter.messagebox.showerror('很抱歉','请选择一个同学')
                return
            defen=comboboxDefen.get()
            if not defen:
                tkinter.messagebox.showerror('很抱歉','请选择得分')
            else:
                #记录该学生得分
                sql="INSERT INTO TIWEN VALUES('"+xueshengXuehao.get()+"','"+Common.getCurrentDateTime()+"','"+defen+"')"
                Common.doSQL(sql)
                if int(defen)>0:
                    tkinter.messagebox.showinfo('太棒了','加分成功')
                elif int(defen)<0:
                    tkinter.messagebox.showinfo('太惨了','被减分了')
        buttonDefen=tkinter.Button(self.top,text='确认得分',command=buttonDefenClick)
        buttonDefen.place(x=130,y=50,height=20,width=80)

        lbInformation=tkinter.Label(self.top,fg='red',textvariable=studentInformation)
        lbInformation.place(x=20,y=100,height=20,width=240)
def buttonTiwenClick():
    if int_windowTiwen.get()==0:
        int_windowTiwen.set(1)
        w1=windowTiwen(root,'随机提问')
        buttonTiwen.wait_window(w1.top)
        int_windowTiwen.set(0)
buttonTiwen=tkinter.Button(root,text='随机提问',command=buttonTiwenClick)
buttonTiwen.place(x=20,y=100,height=30,width=100)

int_windowChakanTiwenQingkuang=tkinter.IntVar(root,value=0)
#====================================================================================
#查看统计情况（成功）
#====================================================================================

class windowChakanTiwenQingkuang:
    def __init__(self,root,myTitle):
        self.top=tkinter.Toplevel(root,width=320,height=380)
        self.top.title(myTitle)
        self.top.attributes('-topmost',1)
        #组合框选择专业，或文本框查看特定学号学生的提问情况
        xueshengZhuanye=Common.getZhuanye()#学生专业
        comboboxZhuanye=tkinter.ttk.Combobox(self.top,values=xueshengZhuanye)
        def comboboxZhuanyeChange(event):
            zhuanye=comboboxZhuanye.get()
            if zhuanye:
                xueshengs=Common.getXuehaoXingming(zhuanye)
                comboboxXuehao['values']=xueshengs
        comboboxZhuanye.bind('<<ComboboxSelected>>',comboboxZhuanyeChange)
        comboboxZhuanye.place(x=20,y=20,height=20,width=120)
        def chakanZhuanye():#查看指定专业所有同学的提问情况
            zhuanye=comboboxZhuanye.get()
            if not zhuanye:
                tkinter.messagebox.showerror('很抱歉','请选择专业')
                return
            else:
                conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
                cur=conn.cursor()
                cur.execute("SELECT STUDENTS.xuehao,STUDENTS.xingming,TIWEN.shijian,TIWEN.defen FROM STUDENTS,TIWEN WHERE STUDENTS.xuehao=TIWEN.xuehao AND STUDENTS.zhuanye='"+zhuanye+"' ORDER BY STUDENTS.xuehao,TIWEN.shijian desc")
                temp=cur.fetchall()
                conn.close()

                for row in treeXueshengMingdan.get_children():#删除原有的所有的行
                    treeXueshengMingdan.delete(row)
                iii=0
                for student in temp:
                    treeXueshengMingdan.insert('',iii,values=(student[0],student[1],student[2],student[3]))
                    iii=iii+1
        buttonZhuanye=tkinter.Button(self.top,text='按专业查看',command=chakanZhuanye)
        buttonZhuanye.place(x=150,y=20,height=20,width=80)
        xueshengXuehao=[]
        comboboxXuehao=tkinter.ttk.Combobox(self.top,values=xueshengXuehao)
        comboboxXuehao.place(x=20,y=60,height=20,width=120)
        def chakanXuehao():
            xuehao=comboboxXuehao.get().split(',')[0]#组合框是“学号，姓名”的格式，需要取出学号信息
            if xuehao=='':
                tkinter.messagebox.showerror('很抱歉','请选择学号')
                return
            else:
                conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
                cur=conn.cursor()
                cur.execute("SELECT STUDENTS.xuehao,STUDENTS.xingming,TIWEN.shijian,TIWEN.defen FROM STUDENTS,TIWEN WHERE STUDENTS.xuehao=TIWEN.xuehao AND STUDENTS.xuehao='"+xuehao+"' ORDER BY TIWEN.shijian desc")
                temp=cur.fetchall()
                conn.close()
                for row in treeXueshengMingdan.get_children():#删除原有的所有行
                    treeXueshengMingdan.delete(row)
                iii=0
                for student in temp:
                    treeXueshengMingdan.insert('',iii,values=(student[0],student[1],student[2],student[3]))
        buttonXuehao=tkinter.Button(self.top,text='按学号查看',command=chakanXuehao)
        buttonXuehao.place(x=150,y=60,height=20,width=80)

        #创建表格，设置表头，show="headings"用来隐藏树形控件的默认首列
        self.frame=tkinter.Frame(self.top)
        self.frame.place(x=20,y=90,width=300,height=280)
        #垂直滚动条
        scrollBar=tkinter.Scrollbar(self.frame)
        scrollBar.pack(side=tkinter.RIGHT,fill=tkinter.Y)
        #用树形控件实现表格
        treeXueshengMingdan=tkinter.ttk.Treeview(self.frame,columns=('col1','col2','col3','col4'),show="headings",yscrollcommand=scrollBar.set)
        treeXueshengMingdan.column('col1',width=70,anchor='center')
        treeXueshengMingdan.column('col2',width=50,anchor='center')
        treeXueshengMingdan.column('col3',width=120,anchor='center')
        treeXueshengMingdan.column('col4',width=40,anchor='center')
        treeXueshengMingdan.heading('col1',text='学号')
        treeXueshengMingdan.heading('col2',text='姓名')
        treeXueshengMingdan.heading('col3',text='提问时间')
        treeXueshengMingdan.heading('col4',text='得分')
        treeXueshengMingdan.pack(side=tkinter.LEFT,fill=tkinter.Y)
        #树形控件与垂直滚动条结合
        scrollBar.config(command=treeXueshengMingdan.yview)
def buttonChakanTiwenQingkuangClick():
    if int_windowChakanTiwenQingkuang.get()==0:
        int_windowChakanTiwenQingkuang.set(1)
        w1=windowChakanTiwenQingkuang(root,'查看提问情况')
        buttonChakanTiwenQingkuang.wait_window(w1.top)
        int_windowChakanTiwenQingkuang.set(0)
buttonChakanTiwenQingkuang=tkinter.Button(root,text='查看提问情况',command=buttonChakanTiwenQingkuangClick)
buttonChakanTiwenQingkuang.place(x=130,y=100,height=30,width=100)

int_windowChakanTongjiQingkuang=tkinter.IntVar(root,value=0)
class windowChakanTongjiQingkuang:
    def __init__(self,root,myTitle):
        self.top=tkinter.Toplevel(root,width=600,height=380)
        self.top.title(myTitle)
        self.top.attributes('-topmost',1)
        #组合框选择专业，或文本框查看特定学号学生的提问情况
        xueshengZhuanye=Common.getZhuanye()#学生专业
        comboboxZhuanye=tkinter.ttk.Combobox(self.top,values=xueshengZhuanye)
        comboboxZhuanye.place(x=20,y=20,height=20,width=120)
        def chakanZhuanye():#查看指定专业所有同学的提问情况
            zhuanye=comboboxZhuanye.get()
            if not zhuanye:
                tkinter.messagebox.showerror('很抱歉','请选择专业')
                return
            else:
                xuehaoXingmings=Common.getXuehaoXingming(zhuanye)
                xuehaos=[xingming.split(',')[0] for xingming in xuehaoXingmings]
                xingmings=[xingming.split(',')[1] for xingming in xuehaoXingmings]
                chuqinCishu=[Common.getChuqinCishu(xuehao) for xuehao in xuehaos]#获取每个同学的出勤次数，缺勤算0，没提问到也算0
                tiwenDefen=[Common.getTiwenDefen(xuehao) for xuehao in xuehaos]
                zhudongTiwenCishu=[Common.getKaoshiDefen(xuehao) for xuehao in xuehaos]
                kaoshidefen = [Common.getKaoshiDefen(xuehao) for xuehao in xuehaos]
                for row in treeXueshengMingdan.get_children():#删除原有的所有行
                    treeXueshengMingdan.delete(row)
                iii=0
                for xuehao, xingming, chuqin, tiwen, zhudongtiwen, kaoshidefen in zip(xuehaos, xingmings, chuqinCishu, tiwenDefen, zhudongTiwenCishu, kaoshidefen):
                    treeXueshengMingdan.insert('', iii, values=(xuehao, xingming, chuqin, tiwen, zhudongtiwen, kaoshidefen))
                    iii=iii+1
        buttonZhuanye=tkinter.Button(self.top,text='按专业查看',command=chakanZhuanye)
        buttonZhuanye.place(x=150,y=20,height=20,width=80)

        #创建表格,设置表头，show="headings"用来隐藏树形控件的默认首列
        self.frame=tkinter.Frame(self.top)
        self.frame.place(x=20,y=50,width=560,height=320)
        #垂直滚动条
        scrollBar=tkinter.Scrollbar(self.frame)
        scrollBar.pack(side=tkinter.RIGHT,fill=tkinter.Y)
        #使用树形控件实现表格
        treeXueshengMingdan=tkinter.ttk.Treeview(self.frame,columns=('col1','col2','col3','col4','col5','col6'),show="headings",yscrollcommand=scrollBar.set)
        treeXueshengMingdan.column('col1',width=70,anchor='center')
        treeXueshengMingdan.column('col2',width=50,anchor='center')
        treeXueshengMingdan.column('col3',width=120,anchor='center')
        treeXueshengMingdan.column('col4',width=120,anchor='center')
        treeXueshengMingdan.column('col5',width=80,anchor='center')
        treeXueshengMingdan.column('col6',width=80,anchor='center')
        treeXueshengMingdan.heading('col1',text='学号')
        treeXueshengMingdan.heading('col2',text='姓名')
        treeXueshengMingdan.heading('col3',text='出勤次数')
        treeXueshengMingdan.heading('col4',text='老师提问得分')
        treeXueshengMingdan.heading('col5',text='主动提问次数')
        treeXueshengMingdan.heading('col6',text='考试得分')
        treeXueshengMingdan.pack(side=tkinter.LEFT,fill=tkinter.Y)
        #树形控件与垂直滚动条结合
        scrollBar.config(command=treeXueshengMingdan.yview)
def buttonChakanTongjiQingkuangClick():
    if int_windowChakanTongjiQingkuang.get()==0:
        int_windowChakanTongjiQingkuang.set(1)
        w1=windowChakanTongjiQingkuang(root,'查看统计情况')
        buttonChakanTongjiQingkuang.wait_window(w1.top)
        int_windowChakanTongjiQingkuang.set(0)
buttonChakanTongjiQingkuang=tkinter.Button(root,text='查看统计情况',command=buttonChakanTongjiQingkuangClick)
buttonChakanTongjiQingkuang.place(x=240,y=100,height=30,width=100)

int_zuoye=tkinter.IntVar(root,value=0)#0,停止收作业。1，开始收作业
def thread_ShouZuoye(conn,today):
    #最终把客户端发来的截图保存为“学号,姓名.jpg”
    #开始接收客户端发来的截图
    BUFSIZE=1024
    FILEINFO_SIZE=struct.calcsize('I128sI')
    fhead=conn.recv(FILEINFO_SIZE)
    filenamelength,filename,filesize=struct.unpack('I128sI',fhead)
    filename=filename.decode()
    print(filename)
    filename=filename[:filenamelength]
    ttt=filename.split('.')[0]
    #如果学号和姓名不匹配，拒绝接收图片作业
    xuehao,xingming=ttt.split(',')
    xuehao=xuehao.replace(';','').replace('"','').replace("'",'').replace('=','')#作用是什么
    xingming=xingming.replace(';','').replace('"','').replace("'",'').replace('=','')#作用是什么
    sql="SELECT count(xuehao) FROM STUDENTS WHERE xuehao='"+xuehao+"' AND xingming='"+xingming.strip()+"'"
    t=Common.getDataBySQL(sql)[0][0]
    if t!=1:
        conn.sendall('notmatch'.encode())
        conn.close()
        return
    else:
        conn.sendall('ok'.encode())
    filename=filename[:-4]+' '.join(Common.getCurrentDateTime().split())+filename[-4:]
    filename=filename.replace('_','')
    filename=filename.replace(':','.')
    filename=today+'\\'+filename
    #首先删除本次作业期间之前上交的作业，只保留最后一次的作业
    for f in os.listdir(today):
        if f.startswith(ttt):
            os.remove(today+'\\'+f)
    fp=open(filename,'wb')
    restsize=filesize
    while True:
        if restsize>BUFSIZE:
            filedata=conn.recv(BUFSIZE)
        else:
            filedata=conn.recv(restsize)
        if not filedata:
            break
        fp.write(filedata)
        restsize=restsize-len(filedata)
        if restsize==0:
            break
    fp.close()
    conn.close()
def thread_ZuoyeMain():
    today=Common.getCurrentDateTime().split()[0]
    if not os.path.exists(today):
        os.mkdir(today)
    #开始监听
    global sockShouzuoye
    sockShouzuoye=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockShouzuoye.bind(('',30100))
    sockShouzuoye.listen(200)
    while int_zuoye.get()==1:
        time.sleep(0.05)
        try:
            conn,addr=sockShouzuoye.accept()
        except:
            return
        t=threading.Thread(target=thread_ShouZuoye,args=(conn,today))
        t.start()
    sock.close()
def buttonStartShouzuoyeClick():
    if int_canDianming.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在点名')
        return
    if int_zuoye.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在收作业，不用重复设置')
        return
    int_zuoye.set(1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在开始收作业')
    t=threading.Thread(target=thread_ZuoyeMain)
    #启动收作业线程
    t.start()
buttonStartShouzuoye=tkinter.Button(root,text='开始收截图作业',command=buttonStartShouzuoyeClick)
buttonStartShouzuoye.place(x=20,y=140,height=30,width=100)

def buttonStopShouzuoyeClick():
    if int_zuoye.get()==0:
        tkinter.messagebox.showerror('很抱歉','还没开始收作业')
        return
    int_zuoye.set(0)
    sockShouzuoye.close()
    time.sleep(0.1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在已停止收作业')
buttonStopShouzuoye=tkinter.Button(root,text='结束收截图作业',command=buttonStopShouzuoyeClick)
buttonStopShouzuoye.place(x=130,y=140,height=30,width=100)
#====================================================================================
#联系作者部分(成功)
#====================================================================================
int_windowLianxiFangshi=tkinter.IntVar(root,value=0)
class windowLianxiFangshi:
    def __init__(self,root,myTitle):
        self.top=tkinter.Toplevel(root,width=420,height=200)
        self.top.title(myTitle)
        self.top.attributes('-topmost',1)
        labelQQ=tkinter.Label(self.top,text='QQ:1029046433',justify=tkinter.LEFT,width=200)
        labelQQ.place(x=20,y=10,height=20,width=200)
        labelEmail=tkinter.Label(self.top,text='Email:1029046433@qq.com',justify=tkinter.LEFT,width=200)
        labelEmail.place(x=20,y=40,height=20,width=200)
        labelWeixin=tkinter.Label(self.top,text='微信：belief1029046433',justify=tkinter.LEFT,width=200)
        labelWeixin.place(x=20,y=70,height=20,width=200)
        labelBeizhu=tkinter.Label(self.top,text='备注：本系统是参考董付国老师的《Python可以这样学》中的相关代码，',justify=tkinter.LEFT,width=200,fg='red')
        labelBeizhu.place(x=20,y=100,height=20,width=420)
        labelBeizhu1=tkinter.Label(self.top,text='实现的，推荐同学们以这本书作为Python入门书，认认真真来学习，一定,',justify=tkinter.LEFT,width=200,fg='red')
        labelBeizhu1.place(x=20,y=120,height=20,width=420)
        labelBeizhu2=tkinter.Label(self.top,text='会有非常大的收获',justify=tkinter.LEFT,width=200,fg='red')
        labelBeizhu2.place(x=20,y=140,height=20,width=420)
def buttonLianxiFangshiClick():
    if int_windowLianxiFangshi.get()==0:
        int_windowLianxiFangshi.set(1)
        w1=windowLianxiFangshi(root,'作者联系方式')
        buttonChakanTongjiQingkuang.wait_window(w1.top)
        int_windowLianxiFangshi.set(0)
buttonLianxiFangshi=tkinter.Button(root,text='联系作者',command=buttonLianxiFangshiClick)
buttonLianxiFangshi.place(x=240,y=140,height=30,width=100)
#====================================================================================
#学生主动提问情况(成功)
#====================================================================================
int_xueshengTiwen=tkinter.IntVar(root,value=0)#控制学生是否可以提问的变量
class windowXueshengTiwen:
    def __init__(self,root,conn,data):
        #创建面板容器，用于放置其他控件
        self.top=tkinter.Toplevel(root,width=300,height=220)
        tttt=tkinter.StringVar(self.top)
        xuehaoXingming,message=data.split(':')
        tttt.set(message)
        self.top.title('来自'+xuehaoXingming+'的消息')
        #把本次学生提问记录添加到数据库
        sqlTiwen="INSERT INTO XUESHENGTIWEN VALUES('"+xuehaoXingming.split(',')[0]+"','"+message+"','"+Common.getCurrentDateTime()+"')"
        Common.doSQL(sqlTiwen)
        #显示窗口
        self.top.attributes('-topmost',1)
        entryMessage=tkinter.scrolledtext.ScrolledText(self.top,wrap=tkinter.WORD)#接收到的消息
        entryMessage.insert(tkinter.INSERT,message)
        entryMessage.place(x=20,y=20,width=250,height=60)
        entryHuifu=tkinter.scrolledtext.ScrolledText(self.top,wrap=tkinter.WORD)#要回复的消息
        entryHuifu.place(x=20,y=90,width=250,height=60)

        def buttonHuifuClick():
            #回复：解答
            huifu=entryHuifu.get(0.0,tkinter.END)
            conn.sendall(huifu.encode())
            conn.close()
            #把本次回复记录添加到数据库
            sqlTiwen="INSERT INTO XUESHENGTIWEN VALUES('"+xuehaoXingming.split(',')[0]+"','老师回复"+xuehaoXingming+":"+huifu+"','"+Common.getCurrentDateTime()+"')"
            Common.doSQL(sqlTiwen)
            #关闭窗口
            self.top.destroy()
        buttonHuifu=tkinter.Button(self.top,text='回复解答',command=buttonHuifuClick)
        buttonHuifu.place(x=40,y=160,width=80,height=20)

        def buttonTongyiJiangjieClick():
            #不回复该问题，稍后统一讲解给全班同学
            conn.sendall('wait'.encode())
            conn.close()
            #把本次回复记录添加到数据库
            sqlTiwen="INSERT INTO XUESHENGTIWEN VALUES('"+xuehaoXingming.split(',')[0]+"','老师回复+"+xuehaoXingming+":该问题稍候统一讲解','"+Common.getCurrentDateTime()+"')"
            Common.doSQL(sqlTiwen)
            #关闭窗口
            self.top.destroy()
        buttonTongyiJiangjie=tkinter.Button(self.top,text='稍候统一讲解',command=buttonTongyiJiangjieClick)
        buttonTongyiJiangjie.place(x=130,y=160,width=80,height=20)

def thread_xueshengTiwenMain():
    global sockTiwen
    sockTiwen=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockTiwen.bind(('',20000))#监听20000端口#+++++++++++++++++++++++++++++++++++++
    sockTiwen.listen(200)#最多允许同时200个学生提问
    while int_xueshengTiwen.get()==1:
        try:
            conn,addr=sockTiwen.accept()#接收一个连接
        except:
            return
        data=conn.recv(1024)#接收消息，消息内容为“学号，姓名：问题内容”
        data=data.decode()
        xuehaoXingming,message=data.split(':')
        xuehao,xingming=xuehaoXingming.split(',')
        xuehao = xuehao.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
        xingming = xingming.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
        print(xuehao,xingming,message)
        sql="SELECT count(xuehao) FROM STUDENTS WHERE xuehao='"+xuehao.strip()+"' AND xingming='"+xingming.strip()+"'"
        t=Common.getDataBySQL(sql)[0][0]
        print(t)
        if t!=1:
            conn.sendall('notmatch'.encode())
            conn.close()
        else:
            w=windowXueshengTiwen(root,conn,data)
    sockTiwen.close()
#启动接收学生提问的线程
def buttonJieshouTiwenClick():
    if int_xueshengTiwen.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在接受提问，不用重复设置')
        return
    int_xueshengTiwen.set(1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在开始接收学生提问')
    t_tiwen=threading.Thread(target=thread_xueshengTiwenMain)
    t_tiwen.start()
buttonJieshouTiwen=tkinter.Button(root,text='开始接收提问',command=buttonJieshouTiwenClick)
buttonJieshouTiwen.place(x=20,y=180,height=30,width=100)

#停止接收学生提问的线程
def buttonTingzhiTiwenClick():
    if int_xueshengTiwen.get()==0:
        tkinter.messagebox.showerror('很抱歉','还没开始接收学生提问')
        return
    int_xueshengTiwen.set(0)
    sockTiwen.close()
    time.sleep(0.1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在停止接收学生提问')
buttonTingzhiTiwen=tkinter.Button(root,text='停止接收提问',command=buttonTingzhiTiwenClick)
buttonTingzhiTiwen.place(x=130,y=180,height=30,width=100)

#查看学生主动提问情况
int_windowXueshengTiwenQingkuang=tkinter.IntVar(root,value=0)
class windowXueshengTiwenQingkuang:
    def __init__(self,root,myTitle):
        self.top=tkinter.Toplevel(root,width=620,height=380)
        self.top.title(myTitle)
        self.top.attributes('-topmost',1)
        #组合框选择专业，或文本框查看特定学号学生的提问情况
        xueshengZhuanye=Common.getZhuanye()#学生专业
        comboboxZhuanye=tkinter.ttk.Combobox(self.top,value=xueshengZhuanye)

        def comboboxZhuanyeChange(event):
            zhuanye=comboboxZhuanye.get()
            if zhuanye:
                xueshengs=Common.getXuehaoXingming(zhuanye)
                comboboxXuehao['values']=xueshengs
        comboboxZhuanye.bind('<<ComboboxSelected>>',comboboxZhuanyeChange)
        comboboxZhuanye.place(x=20,y=20,height=20,width=120)

        def chakanZhuanye():#查看指定专业所有同学的提问情况
            zhuanye=comboboxZhuanye.get()
            if not zhuanye:
                tkinter.messagebox.showerror('很抱歉','请选择专业')
                return
            else:
                conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
                cur=conn.cursor()
                cur.execute("SELECT STUDENTS.xuehao,STUDENTS.xingming,XUESHENGTIWEN.wenti,XUESHENGTIWEN.shijian FROM STUDENTS,XUESHENGTIWEN WHERE STUDENTS.xuehao=XUESHENGTIWEN.xuehao AND STUDENTS.zhuanye='"+zhuanye+"' ORDER BY STUDENTS.xuehao,XUESHENGTIWEN.shijian desc")
                temp=cur.fetchall()
                conn.close()
                for row in treeXueshengMingdan.get_children():#删除原有的所有行
                    treeXueshengMingdan.delete(row)
                iii=0
                for student in temp:
                    treeXueshengMingdan.insert('',iii,values=(student[0],student[1],student[2],student[3]))
                    iii=iii+1
        buttonZhuanye=tkinter.Button(self.top,text='按专业查看',command=chakanZhuanye)
        buttonZhuanye.place(x=150,y=20,height=20,width=80)
        xueshengXuehao=[]
        comboboxXuehao=tkinter.ttk.Combobox(self.top,values=xueshengXuehao)
        comboboxXuehao.place(x=20,y=60,height=20,width=120)

        def chakanXuehao():
            xuehao=comboboxXuehao.get().split(',')[0]#组合框是“学号，姓名”的格式，需要取出学号信息
            if xuehao=='':
                tkinter.messagebox.showerror('很抱歉','请选择学号')
                return
            else:
                conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
                cur=conn.cursor()
                cur.execute("SELECT STUDENTS.xuehao,STUDENTS.xingming,XUESHENGTIWEN.wenti,XUESHENGTIWEN.shijian FROM STUDENTS,XUESHENGTIWEN WHERE STUDENTS.xuehao=XUESHENGTIWEN.xuehao AND STUDENTS.xuehao='"+xuehao+"' ORDER BY XUESHENGTIWEN.shijian desc")
                temp=cur.fetchall()
                conn.close()
                for row in treeXueshengMingdan.get_children():#删除原有的所有行
                    treeXueshengMingdan.delete(row)
                iii=0
                for student in temp:
                    treeXueshengMingdan.insert('',iii,values=(student[0],student[1],student[2],student[3]))
                    iii=iii+1
        buttonXuehao=tkinter.Button(self.top,text='按学号查看',command=chakanXuehao)
        buttonXuehao.place(x=150,y=60,height=20,width=80)

        #创建表格,设置表头，show="headings"用来隐藏树形控件的默认首列
        self.frame=tkinter.Frame(self.top)
        self.frame.place(x=10,y=90,width=600,height=280)
        #垂直滚动条
        scrollBar=tkinter.Scrollbar(self.frame)
        scrollBar.pack(side=tkinter.RIGHT,fill=tkinter.Y)
        #使用树形控件实现表格
        treeXueshengMingdan=tkinter.ttk.Treeview(self.frame,columns=('col1','col2','col3','col4','col4'),show="headings",yscrollcommand=scrollBar.set)
        treeXueshengMingdan.column('col1',width=70,anchor='center')
        treeXueshengMingdan.column('col2',width=50,anchor='center')
        treeXueshengMingdan.column('col3',width=320,anchor='center')
        treeXueshengMingdan.column('col4',width=140,anchor='center')
        treeXueshengMingdan.heading('col1',text='学号')
        treeXueshengMingdan.heading('col2',text='姓名')
        treeXueshengMingdan.heading('col3',text='问题')
        treeXueshengMingdan.heading('col4',text='时间')
        treeXueshengMingdan.pack(side=tkinter.LEFT,fill=tkinter.Y)
        #树形控件与垂直滚动条结合
        scrollBar.config(command=treeXueshengMingdan.yview)

def buttonChakanTiwenQingkuangClick():
    if int_windowXueshengTiwenQingkuang.get()==0:
        int_windowXueshengTiwenQingkuang.set(1)
        w1=windowXueshengTiwenQingkuang(root,'学生主动提问情况')
        buttonXueshengTiwenQingkuang.wait_window(w1.top)
        int_windowXueshengTiwenQingkuang.set(0)
buttonXueshengTiwenQingkuang=tkinter.Button(root,text='学生主动提问情况',command=buttonChakanTiwenQingkuangClick)
buttonXueshengTiwenQingkuang.place(x=240,y=180,height=30,width=100)
#==============================================================
#学生自学模块（自测）（成功）
#==============================================================
int_xueshengZixue=tkinter.IntVar(root,value=0)#控制学生是否可以自测的变量
def thread_xueshengZixue(conn):
    data=conn.recv(1024)#接收学号和姓名，记录提问访问情况
    data=data.decode()
    xuehao,xingming=data.split(',')
    xuehao = xuehao.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
    xingming = xingming.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
    sqlTikuFangwen="INSERT INTO TIKUFANGWENQINGKUANG VALUES ('"+xuehao+"','"+xingming+"','"+Common.getCurrentDateTime()+"')"
    Common.doSQL(sqlTikuFangwen)
    #获取并向客户端发送题库中的课程名称，以逗号隔开
    sqlKechengMingcheng="SELECT distinct(kechengmingcheng) FROM TIKU"
    kechengQingdan=[]
    for kecheng in Common.getDataBySQL(sqlKechengMingcheng):
        kechengQingdan.append(str(kecheng[0]))
    kechengQingdan=','.join(kechengQingdan)
    conn.sendall(kechengQingdan.encode())
    #开始接收课程名字，当前学号id、上一题，下一题，返回课程名称、章节、题号id、题干，答案，没有上一题或者下一题的则返回no
    #如果客户端发来的是xxxx,表示结束自测
    while int_xueshengZixue.get()==1:
        data=conn.recv(1024)
        data=data.decode()
        print(data)
        if data=='xxxx':
            conn.recv(1024)
            break
        kechengmingcheng,currentID,pre_next=data.split('xx')
        if pre_next=='pre':
            sqlHasmore="SELECT kechengmingcheng,zahngjie,timu,daan,id FROM TIKU WHERE kechengmingcheng='"+kechengmingcheng+"' AND id<"+currentID+" ORDER BY id DESC"
            ttt=Common.getDataBySQL(sqlHasmore)
            if ttt:
                tttt=ttt[0]
                message=tttt[0]+'xx'+tttt[1]+'xx'+tttt[2]+'xx'+tttt[3]+'xx'+str(tttt[4])
                conn.sendall(message.encode())
            else:
                conn.sendall('no'.encode())
        elif pre_next=='next':#下一题
            sqlHasmore="SELECT kechengmingcheng,zahngjie,timu,daan,id FROM TIKU WHERE kechengmingcheng='"+kechengmingcheng+"' AND id>'"+currentID+"' ORDER BY id"
            ttt=Common.getDataBySQL(sqlHasmore)
            if ttt:
                tttt=ttt[0]
                message=tttt[0]+'xx'+tttt[1]+'xx'+tttt[2]+'xx'+tttt[3]+'xx'+str(tttt[4])
                conn.sendall(message.encode())
            else:
                conn.sendall('no'.encode())
    conn.close()
def thread_xueshengZixueMain():
    global sockZice
    sockZice=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockZice.bind(('',10000))#监听10000端口
    sockZice.listen(200)#最多允许200个学生同时提问
    while int_xueshengZixue.get()==1:
        try:
            conn,addr=sockZice.accept()#接收一个连接
        except:
            return
        t_zixue=threading.Thread(target=thread_xueshengZixue,args=(conn,))
        t_zixue.start()
    sockZice.close()
#启动学生自测的线程
def buttonStartXueshengZixueClick():
    if int_xueshengZixue.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在进行学生自测，不用重复设置')
        return
    int_xueshengZixue.set(1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在开始学生自测')
    t_tiwen=threading.Thread(target=thread_xueshengZixueMain)
    t_tiwen.start()
buttonStartXueshengZixue=tkinter.Button(root,text='开始学生自测',command=buttonStartXueshengZixueClick)
buttonStartXueshengZixue.place(x=130,y=220,height=30,width=100)

#停止学生自测的线程
def buttonStopXueshengZixueClick():
    if int_xueshengZixue.get()==0:
        tkinter.messagebox.showerror('很抱歉','现在不是学生自测时间')
        return
    int_xueshengZixue.set(0)
    sockZice.close()
    tkinter.messagebox.showinfo('恭喜','设置成功，现在停止学生自测')
buttonStopXueshengZixue=tkinter.Button(root,text='停止学生自测',command=buttonStopXueshengZixueClick)
buttonStopXueshengZixue.place(x=240,y=220,height=30,width=100)

int_wenjianZuoye=tkinter.IntVar(root,value=0)
#====================================================
#负责具体文件作业的线程
#====================================================
def thread_ShouwenJianzuoye(conn,today):
    BUFSIZE=1024
    FILEINFO_SIZE=struct.calcsize('I128sI')
    fhead=conn.recv(FILEINFO_SIZE)
    filenamelength,filename,filesize=struct.unpack('I128sI',fhead)
    filename=filename.decode()
    filename=filename[:filenamelength]
    print(filename)

    ttt=filename.split('_1_')[0]
    #如果学号和姓名不匹配，拒绝接收作业
    xuehao,xingming=ttt.split('_')
    xuehao = xuehao.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
    xingming = xingming.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
    sql="SELECT count(xuehao) FROM STUDENTS WHERE xuehao='"+xuehao.strip()+"' AND xingming='"+xingming.strip()+"'"
    t=Common.getDataBySQL(sql)[0][0]
    if t!=1:
        conn.sendall('notmatch'.encode())
        conn.close()
        return
    else:
        conn.sendall('ok'.encode())
    index=filename.rindex('.')
    filename=xuehao+'_'+xingming+'_'.join(Common.getCurrentDateTime()[:19])+filename[index:]
    filename=filename.replace('_','')
    filename=filename.replace(':','.')
    filename=today+'\\'+filename
    print(filename)

    #首先删除本次作业期间之前交的作业，只保留最后一次的作业
    for f in os.listdir(today):
        if f.startswith(ttt):
            os.remove(today+'\\'+f)
    fp=open(filename,'wb')
    restsize=filesize
    while True:
        if restsize>BUFSIZE:
            filedata=conn.recv(BUFSIZE)
        else:
            filedata=conn.recv(restsize)
        if not filedata:
            break
        fp.write(filedata)
        restsize=restsize-len(filedata)
        if restsize==0:#文件已经读完
            break
    fp.close()
    conn.close()
#负责监听端口的收文件作业主线程函数
def thread_WenjianZuoyeMain():
    today=Common.getCurrentDateTime().split()[0]
    if not os.path.exists(today):
        os.mkdir(today)
    #开始监听
    global sockShouWenjianZuoye
    sockShouWenjianZuoye=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockShouWenjianZuoye.bind(('',10500))
    sockShouWenjianZuoye.listen(200)
    while int_wenjianZuoye.get()==1:
        time.sleep(0.05)
        try:
            conn,addr=sockShouWenjianZuoye.accept()
        except:
            return
        t=threading.Thread(target=thread_ShouwenJianzuoye,args=(conn,today))
        t.start()
    sockShouWenjianZuoye.close()
#开始接收学生上传的python程序文件作业
def buttonStartJieshouWenjianZuoyeClick():
    if int_wenjianZuoye.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在收作业，不用重复设置')
        return
    int_wenjianZuoye.set(1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在开始收作业')
    t=threading.Thread(target=thread_WenjianZuoyeMain)
    #启动收作业线程
    t.start()
buttonStartJieshouWenjianZuoye=tkinter.Button(root,text='开始收文件作业',command=buttonStartJieshouWenjianZuoyeClick)
buttonStartJieshouWenjianZuoye.place(x=20,y=260,height=30,width=100)

#结束收学生上传的文件作业
def buttonStopJieshouWenjianZuoyeClick():
    if int_wenjianZuoye.get()==0:
        tkinter.messagebox.showerror('很抱歉','还没开始收作业')
        return
    int_wenjianZuoye.set(0)
    sockShouWenjianZuoye.close()
    time.sleep(0.1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在开始停止收作业')
buttonStopJieshouWenjianZuoye=tkinter.Button(root,text='结束收文件作业',command=buttonStopJieshouWenjianZuoyeClick)
buttonStopJieshouWenjianZuoye.place(x=130,y=260,height=30,width=100)
#==================================================================
#数据导出到xlxs文件中(未成功)
#==================================================================
def buttonDaochuClick():
    try:
        import openpyxl
        from tkinter import simpledialog
        from openpyxl import Workbook
    except:
        tkinter.messagebox.showerror('抱歉','你需要装openpyxl扩展库')

    #设置要导出数据的时间段
    while True:
        startTime=simpledialog.askstring('请输入开始时间','开始时间:',initialvalue='2018-04-19')
        try:
            import datetime
            #确保输入的是正确的日期格式
            y,m,d=map(int,startTime.split('-'))
            startTime=str(datetime.date(y,m,d))
        except:
            pass
        else:
            break
    while True:
        endTime=simpledialog.askstring('请输入结束时间','结束时间：',initialvalue='2018-04-25')
        try:
            import datetime
            #确保输入的是正确的日期格式
            y,m,d=map(int,endTime.split('-'))
            endTime=str(datetime.date(y,m,d))
        except:
            pass
        else:
            break
    #统一的时间段条件
    shijianDuan='shijian>="'+startTime+'"AND shijian<="'+endTime+'"'
    wb=Workbook()
    #删除默认的worksheet
    #wb.remove_sheet(wb.worksheets[0])
    #点名记录
    ws=wb.create_sheet(title='在线点名情况')
    ws.append(['学号','姓名','点名时间'])
    sql="SELECT STUDENTS.xuehao,STUDENTS.xingming,shijian FROM STUDENTS,DIANMING WHERE STUDENTS.xuehao=DIANMING.xuehao AND shijian<='2017-9-25' and shijian>='2017-9-23' ORDER BY STUDENTS.xuehao,shijian"
    print(data)
    for d in data:
        ws.append([d[0],d[1],d[2]])
    #提问情况
    ws=wb.create_sheet(title='随机提问与加分情况')
    ws.append(['学号','姓名','提问时间','得分'])
    sql="SELECT STUDENTS.xuehao,STUDENTS.xingming,shijian,defen FROM STUDENTS,TIWEN WHERE STUDENTS.xuehao=TIWEN.xuehao AND shijian<='2018-04-25' and shijian>='2018-04-15' ORDER BY STUDENTS.xuehao"
    data=Common.getDataBySQL(sql)
    for d in data:
        ws.append([d[0],d[1],d[2],d[3]])
    #题库访问情况
    ws=wb.create_sheet(title='题库访问情况')
    ws.append(['学号','姓名','访问时间'])
    sql="SELECT xuehao,xingming,shijian FROM TIKUFANGWENQINGKUANG WHERE shijian<='2018-04-25' and shijian>='2018-04-18' ORDER BY xuehao"
    data=Common.getDataBySQL(sql)
    for d in data:
        ws.append([d[0],d[1],d[2]])
    #考试情况
    ws=wb.create_sheet(title='考试情况')
    ws.append(['学号','姓名','答题时间','题干','标准答案','学生答案','是否正确'])
    sql="select xuehao,xingming,shijian,timu,daan,xueshengdaan,shifouzhengque from kaoshi,tiku where tiku.id=kaoshi.timubiaohao and shijian<='2018-04-23' and shijian>='2018-04-19' order by xuehao,shijian"
    data=Common.getDataBySQL(sql)
    for d in data:
        ws.append([d[0],d[1],d[2],d[3],d[4],d[5],d[6]])
    wb.save('数据导出.xlsx')
    tkinter.messagebox.showinfo('恭喜','数据导出成功，请查看系统文件中的“数据导出.xlsx文件”')
buttonDaochu=tkinter.Button(root,text='数据导出',command=buttonDaochuClick)
buttonDaochu.place(x=240,y=260,height=30,width=100)
#在线考试模块
int_xueshengKaoshi=tkinter.IntVar(root,value=0)#控制学生是否可以自测的变量
def thread_xueshengKaoshi(conn):
    data=conn.recv(1024)#接收学号和姓名
    data=data.decode()
    xuehao,xingming=data.split(',')
    xuehao = xuehao.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
    xingming = xingming.replace(';', '').replace('"', '').replace("'", '').replace('=', '')
    #检查学号和姓名是否匹配和正确
    sql="SELECT count(xuehao) FROM STUDENTS WHERE xuehao='"+xuehao.strip()+"' AND xingming='"+xingming.strip()+"'"
    t=Common.getDataBySQL(sql)[0][0]
    if t!=1:
        conn.sendall('notmatch'.encode())
        conn.close()
        return
    else:
        conn.sendall('ok'.encode())

    sqlTikuFangwen="INSERT INTO TIKUFANGWENQINGKUANG VALUES('"+xuehao+"','"+xingming+"','"+Common.getCurrentDateTime()+"')"
    Common.doSQL(sqlTikuFangwen)
    #获取并向客户端发送题库中的课程名称，以逗号展开
    sqlKechengmingcheng="SELECT distinct(kechengmingcheng) FROM TIKU"
    kechengQingdan=[]
    for kecheng in Common.getDataBySQL(sqlKechengmingcheng):
        kechengQingdan.append(str(kecheng[0]))
    kechengQingdan=','.join(kechengQingdan)
    conn.sendall(kechengQingdan.encode())
    #开始接收课程名称，当前题号id，上一题/下一题，返回课程名称，章节，题号id，题干，答案，没有上一题或下一题则返回no
    #如果客户端发来xxxx,表示考试自测
    while int_xueshengKaoshi.get()==1:
        data=conn.recv(1024)
        data=data.decode()
        print('客户端传过来的数据：'+data)
        if data=='xxxx':
            conn.recv(1024)
            break
        kechengmingcheng,currentID,daan,pre_next=data.split('xx')
        print('课程名称：'+kechengmingcheng)
        print('当前题目ID号：'+currentID)
        print('学生答案：'+daan)
        print('指向问题的指针'+pre_next)
        if  pre_next=='next':#下一题
            #把本题学生答案记录，不记录0号题
            if currentID!='0':
                print('标准答案：'+biaozhundaan)
                if daan==biaozhundaan:#学生答案正确
                    shifouzhengque='Y'
                #填空题，help和help()两种形式答案都算对    
                elif biaozhundaan.endswith('()') and daan==biaozhundaan[:-2]:
                    shifouzhengque='Y'
                #如果标准答案中有空格，重新修正学生答案，考虑学生输入多个空格的情况
                elif ' '.join(biaozhundaan.split())==' '.join(daan.split()):
                    shifouzhengque='Y'
                elif ''.join(biaozhundaan.split())==''.join(daan.split()):#考虑学生没有输入空格的情况
                    shifouzhengque='Y'
                else:
                    shifouzhengque='N'
                print('是否正确：'+shifouzhengque)
                sql='INSERT INTO KAOSHI VALUES("'+currentID+'","'+xuehao+'","'+xingming+'","'+Common.getCurrentDateTime()+'","'+currentID+'","'+daan+'","'+biaozhundaan+'","'+shifouzhengque+'")'
                Common.doSQL(sql)

            #判断学生是否已经答了100道，若是，则不允许再继续答题
            sql="select count(xuehao) from kaoshi where xuehao='"+xuehao+"'"
            total=Common.getDataBySQL(sql)[0]
            print(total)
            if total[0]>=9:
                a=conn.sendall(('no'+str(Common.getKaoshiDefen(xuehao))).encode())
                print('当a>9时，执行，统计得分'+str(Common.getKaoshiDefen(xuehao)))
                print('====================================')
                break
            #发送下一题
            r=random.random()
            #print(r)
            sqlHasMore="select kechengmingcheng,zahngjie,timu,id,daan from tiku where kechengmingcheng='"+kechengmingcheng+"' and id not in (select timubiaohao from kaoshi where xuehao='"+xuehao+"')order by '"+str(int(r))+"' limit 1"
            ttt=Common.getDataBySQL(sqlHasMore)
            if ttt:
                tttt=ttt[0]
                message=tttt[0]+'xx'+tttt[1]+'xx'+tttt[2]+'xx'+str(tttt[3])+'xx'+str(total[0])#total0表示已做过多少题
                print('给客户端传过去的值'+message)
                #记录本题大难，评分用
                biaozhundaan=str(tttt[4])
                conn.sendall(message.encode())
            else:
                conn.sendall(('no'+str(Common.getDataBySQL(sql))).encode())
    conn.close()
def thread_xueshengKaoshiMian():
    global sockKaoshi
    sockKaoshi=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockKaoshi.bind(('',18002))
    sockKaoshi.listen(200)
    while int_xueshengKaoshi.get()==1:
        try:
            conn,addr=sockKaoshi.accept()#接收一个链接
        except:
            return
        t_Kaoshi=threading.Thread(target=thread_xueshengKaoshi,args=(conn,))
        t_Kaoshi.start()
    sockKaoshi.close()
#开始考试按钮
def buttonStartKaoshiClick():
    if int_xueshengKaoshi.get()==1:
        tkinter.messagebox.showerror('很抱歉','现在正在考试，不用重复设置')
        return
    int_xueshengKaoshi.set(1)
    tkinter.messagebox.showinfo('恭喜','设置成功，现在开始开始')
    t_Kaoshi=threading.Thread(target=thread_xueshengKaoshiMian)
    t_Kaoshi.start()
buttonStartKaoshi=tkinter.Button(root,text='开始考试',command=buttonStartKaoshiClick)
buttonStartKaoshi.place(x=20,y=300,height=30,width=100)

#结束考试按钮
def buttonStopKaoshiClick():
    if int_xueshengKaoshi.get()==0:
        tkinter.messagebox.showerror('很抱歉','现在不是考试时间')
        return
    int_xueshengKaoshi.set(0)
    sockKaoshi.close()
    tkinter.messagebox.showinfo('恭喜','设置成功，现在停止考试')
buttonStopKaoshi=tkinter.Button(root,text='结束考试',command=buttonStopKaoshiClick)
buttonStopKaoshi.place(x=130,y=300,height=30,width=100)

#清空所有学生考试数据
def butonDeleteKaoshiShujuClick():
    if tkinter.messagebox.askyesno('确定','确定要删除吗？')==tkinter.YES:
        sql="delete from kaoshi"
        Common.doSQL(sql)
        tkinter.messagebox.showinfo('恭喜','删除成功')
butonDeleteKaoshiShuju=tkinter.Button(root,text='删除考试数据',command=butonDeleteKaoshiShujuClick)
butonDeleteKaoshiShuju.place(x=240,y=300,height=30,width=100)

#生成word试卷
def buttonGenerateShijiuanClick():
    num=simpledialog.askinteger('请输入题目数量','题目数量')
    if not num:
        return
    conn=pymysql.connect("localhost","root","womenilu2580","stmanagement",charset='utf8')
    cur=conn.cursor()
    cur.execute('select timu,daan from tiku')
    temp=cur.fetchall()
    conn.close()
    temp=random.sample(temp,num)
    yesno=tkinter.messagebox.askyesno('按题型排序吗?','按题型排序吗？')
    if yesno:
        #对题目类型排序，填空题在前，判断题在后
        temp.sort(key=lambda item:item[:3],reverse=True)
    from docx import Document
    document=Document()
    document.add_paragraph('试题')
    for i,t in enumerate(temp):
        document.add_paragraph(str(i+1)+'、'+t[0])
    document.add_page_break()
    document.add_paragraph('答案')
    for i,t in enumerate(temp):
        document.add_paragraph(str(i+1)+'、'+t[1])
    document.save('试卷_答案.docx')
    tkinter.messagebox.showinfo('恭喜','生成时间成功')
    os.startfile('试卷_答案.docx')
buttonGenerateShijiuan=tkinter.Button(root,text='生成word试卷',command=buttonGenerateShijiuanClick)
buttonGenerateShijiuan.place(x=20,y=340,height=30,width=100)

root.mainloop()
        


            
            
    
            
        
        
    
            
    
        
    
    
        
        
        
        

        
        
                
                
            
        
            
        
